package pe.gob.foncodes.ssa.bs.common.util;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.engine.util.JRSaver;

/**
 *
 */
public class SerializedList<E> extends ArrayList<E> {

    private static final String TEMP_FILE_PREFIX = "JasperPrint";
    private static final long serialVersionUID = -2049674891904716923L;

    @Override
    public boolean add(E e) {
        return super.add((E)serializeToTempFile(e));
    }

    @Override
    public E get(int index) {
        Object e = super.get(index);
        if (!(e instanceof File)) {
            throw new RuntimeException("Found a non-File element in the list");
        }
        return (E)deserializeFromTempFile((File) e);
    }

    public void dispose() {
        for (int idx = 0; idx < size(); ++idx) {
            Object e = super.get(idx);
            if (e instanceof File) {
                File temp = (File) e;
                temp.delete();
            }
        }
        super.clear();
    }

    protected File serializeToTempFile(Object o) {
        try {
            File tempFile = File.createTempFile(TEMP_FILE_PREFIX, null);
            JRSaver.saveObject(o, tempFile);
            return tempFile;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (JRException e) {
            throw new RuntimeException(e);
        }
    }

    protected Object deserializeFromTempFile(File temp) {
        try {
            return JRLoader.loadObject(temp);
        } catch (JRException e) {
            throw new RuntimeException(e);
        }
    }
}